package cn.shengchao.qywx.remote.rpc;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.shengchao.examstar.rpc.wecom.api.WeComSyncToLocalApi;
import cn.shengchao.examstar.rpc.wecom.dto.ExternalContactUserDto;
import cn.shengchao.examstar.rpc.wecom.dto.WeComCpUserDto;
import cn.shengchao.examstar.rpc.wecom.dto.WeComDeptUserDto;
import cn.shengchao.qywx.infrastrure.po.QywxCustomer;
import cn.shengchao.qywx.infrastrure.po.QywxUser;
import cn.shengchao.qywx.infrastrure.po.QywxUserCustomer;
import cn.shengchao.qywx.infrastrure.service.QywxCustomerService;
import cn.shengchao.qywx.infrastrure.service.QywxUserCustomerService;
import cn.shengchao.qywx.infrastrure.service.QywxUserService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: examstarapi
 * @description: 企微同步到本地数据库的APi实现
 * @author: Xiong weiqiang
 * @create: 2025-04-10 13:51
 */
@DubboService
@RequiredArgsConstructor
public class WeComSyncToLocalDubboApi implements WeComSyncToLocalApi {
    private final QywxUserService qywxUserService;
    private final QywxUserCustomerService qywxUserCustomerService;
    private final QywxCustomerService qywxCustomerService;

    @Transactional
    @Override
    public void syncDeptUserList(List<WeComDeptUserDto> deptUserDtoList) {
            if (CollUtil.isNotEmpty(deptUserDtoList)){
                List<QywxUser> qywxUsers=qywxUserService.list(Wrappers.lambdaQuery(QywxUser.class).in(QywxUser::getUserId,deptUserDtoList.stream().map(WeComDeptUserDto::getUserId).collect(Collectors.toSet())));
                List<String> existsUserIds=qywxUsers.stream().map(QywxUser::getUserId).toList();
                List<QywxUser> needSaveQywxUsers=deptUserDtoList.stream().filter(weComDeptUserDto -> !existsUserIds.contains(weComDeptUserDto.getUserId())).map(weComDeptUserDto -> {
                    QywxUser qywxUser=new QywxUser();
                    qywxUser.setUserId(weComDeptUserDto.getUserId());
                    qywxUser.setName(weComDeptUserDto.getUserId());
                    qywxUser.setDepartment(weComDeptUserDto.getDepartment());
                    qywxUser.setLoadStatus(0);
                    qywxUser.setLastUpdateTime(new Date());
                    qywxUser.setStatus(1);
                    return qywxUser;
                }).toList();
                qywxUserService.saveBatch(needSaveQywxUsers);
            }
    }

    private void saveOrUpdate(List<WeComDeptUserDto> deptUserDtoList, int segment,int index){
         int currentLimit=index+segment;
         if (currentLimit>deptUserDtoList.size()-1){
             currentLimit=deptUserDtoList.size()-1;
         }
         System.out.println("分段处理企微用户数据：从"+index+"到"+currentLimit+"条数据");
         List<WeComDeptUserDto> deptUserDtoListSegment=deptUserDtoList.subList(index,currentLimit);
         List<QywxUser> qywxUsers=qywxUserService.list(Wrappers.lambdaQuery(QywxUser.class).in(QywxUser::getUserId,deptUserDtoListSegment.stream().map(WeComDeptUserDto::getUserId).collect(Collectors.toSet())));
         List<String> existsUserIds=qywxUsers.stream().map(QywxUser::getUserId).toList();
         List<QywxUser> needSaveQywxUsers=deptUserDtoListSegment.stream().filter(weComDeptUserDto -> !existsUserIds.contains(weComDeptUserDto.getUserId())).map(weComDeptUserDto -> {
             QywxUser qywxUser=new QywxUser();
             qywxUser.setUserId(weComDeptUserDto.getUserId());
             qywxUser.setName(weComDeptUserDto.getUserId());
             qywxUser.setDepartment(weComDeptUserDto.getDepartment());
             qywxUser.setLoadStatus(0);
             qywxUser.setLastUpdateTime(new Date());
             qywxUser.setStatus(1);
             return qywxUser;
         }).toList();
         qywxUserService.saveBatch(needSaveQywxUsers);
         if (currentLimit<deptUserDtoList.size()-1){
             saveOrUpdate(deptUserDtoList,segment,currentLimit+1);
         }
    }
    @Transactional
    @Override
    public void syncUserInfoToLocal(WeComCpUserDto weComCpUserDto) {
        if (weComCpUserDto!=null&&weComCpUserDto.getUserId()!=null){
            QywxUser qywxUser=qywxUserService.getOne(Wrappers.lambdaQuery(QywxUser.class).eq(QywxUser::getUserId,weComCpUserDto.getUserId()));
            if (qywxUser!=null){
                //如果是换了id
                if (StrUtil.isNotBlank(weComCpUserDto.getNewUserId())){
                    qywxUserService.update(Wrappers.lambdaUpdate(QywxUser.class).set(QywxUser::getStatus,2).eq(QywxUser::getUserId,weComCpUserDto.getUserId()));
                    qywxUser.setId(null);
                }
                qywxUser.setName(weComCpUserDto.getName());
                qywxUser.setDepartment(Arrays.toString(weComCpUserDto.getDepartIds()));
                qywxUser.setAlias(weComCpUserDto.getAlias());
                qywxUser.setMainDepartment(weComCpUserDto.getMainDepartment());
                qywxUser.setEmail(weComCpUserDto.getEmail());
                qywxUser.setAddress(weComCpUserDto.getAddress());
                qywxUser.setAvatar(weComCpUserDto.getAvatar());
                qywxUser.setBizEmail(weComCpUserDto.getBizMail());
                qywxUser.setThumbAvatar(weComCpUserDto.getThumbAvatar());
                qywxUser.setTelephone(weComCpUserDto.getTelephone());
                qywxUser.setPosition(weComCpUserDto.getPosition());
                qywxUser.setStatus(weComCpUserDto.getStatus());
                qywxUser.setDirectLeader(Arrays.toString(weComCpUserDto.getDirectLeader()));
                qywxUser.setLoadStatus(1);
                qywxUser.setOpenUserId(weComCpUserDto.getOpenUserId());
                qywxUser.setIsLeaderInDept(Arrays.toString(weComCpUserDto.getIsLeaderInDept()));
                qywxUser.setLastUpdateTime(new Date());
                qywxUserService.saveOrUpdate(qywxUser);
            }
        }
    }

    /**
     * 检查用户的客户联系功能
     * @param followUserIds
     */
    @Override
    public void syncLocalUserFollows(List<String> followUserIds) {
        if (CollUtil.isNotEmpty(followUserIds)){
            List<QywxUser> qywxUserList=qywxUserService.list(Wrappers.lambdaQuery(QywxUser.class).notIn(QywxUser::getUserId,followUserIds));
            if (CollUtil.isNotEmpty(qywxUserList)){
                qywxUserService.update(Wrappers.lambdaUpdate(QywxUser.class).in(QywxUser::getUserId,qywxUserList.stream().map(QywxUser::getUserId).toList()).set(QywxUser::getAsFollower,0));
            }
            qywxUserService.update(Wrappers.lambdaUpdate(QywxUser.class).in(QywxUser::getUserId,followUserIds).set(QywxUser::getAsFollower,1));
        }
    }

    /**
     * 更新对外成员的外部联系人id
     * @param userId
     * @param customers
     */
    @Transactional
    @Override
    public void syncLocalUserCustomers(String userId, List<String> customers) {
        if (CollUtil.isNotEmpty(customers)){
            qywxUserCustomerService.remove(Wrappers.lambdaQuery(QywxUserCustomer.class).eq(QywxUserCustomer::getQywxUserId,userId));
            List<QywxUserCustomer> qywxUserCustomers=customers.stream().map(customer->{
                QywxUserCustomer qywxUserCustomer=new QywxUserCustomer();
                qywxUserCustomer.setQywxUserId(userId);
                qywxUserCustomer.setExternalUserid(customer);
                return qywxUserCustomer;
            }).toList();
            qywxUserCustomerService.saveBatch(qywxUserCustomers);
            List<QywxCustomer> list=qywxCustomerService.list(Wrappers.lambdaQuery(QywxCustomer.class).in(QywxCustomer::getExternalUserId,customers));
            customers.removeAll(list.stream().map(QywxCustomer::getExternalUserId).toList());

            //保存客户id
            if (CollUtil.isNotEmpty(customers)){
                List<QywxCustomer> qywxCustomers=customers.stream().map(customer->{
                    QywxCustomer qywxCustomer=new QywxCustomer();
                    qywxCustomer.setExternalUserId(customer);
                    qywxCustomer.setLoadStatus(0);
                    return qywxCustomer;
                }).toList();
                qywxCustomerService.saveBatch(qywxCustomers);
            }
        }
    }

    @Override
    public void syncExternalUserCustomerDetail(ExternalContactUserDto externalContactUserDto) {
        QywxCustomer qywxCustomer=qywxCustomerService.getOne(Wrappers.lambdaQuery(QywxCustomer.class).eq(QywxCustomer::getExternalUserId,externalContactUserDto.getExternalUserId()).eq(QywxCustomer::getLoadStatus,0));
        if (qywxCustomer==null){
            qywxCustomer=new QywxCustomer();
        }
        System.out.println("外部联系人详情："+JSONUtil.toJsonStr(externalContactUserDto));
        BeanUtil.copyProperties(externalContactUserDto,qywxCustomer);
        qywxCustomer.setLoadStatus(1);
        qywxCustomerService.saveOrUpdate(qywxCustomer);
    }
}